import pyglet
import cv2
import numpy as np
import time


def read_bin_image(path):
    # resource = cv2.imread('../resource/1.png', cv2.IMREAD_UNCHANGED)
    img = cv2.imread(path, cv2.IMREAD_UNCHANGED)
    b, g, r, a = cv2.split(img)
    a = cv2.copyMakeBorder(a, 50, 50, 50, 50, cv2.BORDER_CONSTANT, value=[0])
    rows, cols = a.shape
    M = cv2.getRotationMatrix2D((cols / 2, rows / 2), 0, 1)
    dst = cv2.warpAffine(a, M, (cols, rows))
    ret, thresh1 = cv2.threshold(dst, 127, 255, cv2.THRESH_BINARY)
    print(thresh1.shape)
    print(thresh1[49][49])
    return thresh1


class BitImage:
    def __init__(self, path, top=0, bottom=0, left=0, right=0):
        # resource = cv2.imread('../resource/1.png', cv2.IMREAD_UNCHANGED)
        img = cv2.imread(path, cv2.IMREAD_UNCHANGED)
        b, g, r, self.a = cv2.split(img)
        self.a = cv2.copyMakeBorder(self.a, top, bottom, left, right, cv2.BORDER_CONSTANT, value=[0])
        self.rows, self.cols = self.a.shape
        self.height, self.width = self.a.shape
        print(self.height, self.width)

    def get_img(self, rotation=0):
        rotation_mat = cv2.getRotationMatrix2D((self.cols / 2, self.rows / 2), rotation, 1)
        dst = cv2.warpAffine(self.a, rotation_mat, (self.cols, self.rows))
        ret, thresh = cv2.threshold(dst, 127, 255, cv2.THRESH_BINARY)
        return thresh


def get_bound(image):
    pyglet.resource.path = ['./resource/']
    pyglet.resource.reindex()

    img = pyglet.resource.image("pipeA.png")

    rawimage = img.get_image_data()
    format = 'A'
    pitch = rawimage.width * len(format)
    pixels = rawimage.get_data(format, pitch)
    print(len(pixels))
    for y in range(rawimage.height):
        for x in range(rawimage.width):
            print(pixels[y * rawimage.height + x])
    i = cv2.imread("resource/bird.png", cv2.IMREAD_UNCHANGED)
    b, g, r, a = cv2.split(i)
    a[63][275] += 10
    print(a[63][275])
    cv2.imshow("123", a)
    cv2.waitKey(1000)
    cv2.waitKey()


if __name__ == '__main__':
    # bird_bit = BitImage("./resource/1.png")
    # cv2.imshow("123", bird_bit.get_img(15))
    # bird_bit1 = BitImage("resource/pipeA.png")
    # cv2.imshow("12333", bird_bit1.get_img(15))
    # cv2.imshow("142333", bird_bit.get_img(85))
    # cv2.waitKey()
    get_bound(1)
